<?php

namespace app\admin\controller;

use app\common\Attribute\ClassTitle;
use app\common\Attribute\RequestMethod;
use app\common\Attribute\RequestTitle;
use think\facade\Request;
use think\file\UploadedFile;
use app\admin\model\Upload as UploadModel;
use app\common\controller\AmisAdminController;
/**
 * 上传
 */
#[ClassTitle('上传')]
class Upload extends AmisAdminController
{
    /**
     * 检查文件哈希是否已存在
     */
    protected function findFileByHash(string $fileHash)
    {
        $existingFile = UploadModel::where('sha1', $fileHash)->find();

        if ($existingFile) {
            return $this->success('文件已存在', [
                'value' => $existingFile['url'],
                'url' => $existingFile['url'],
                'name' => $existingFile['original_name'],
                'size' => $existingFile['size'],
                'id' => $existingFile['id']
            ]);
        }

        return false;
    }
    /**
     * 保存文件信息到数据库
     */
    protected function saveFileToDatabase(UploadedFile $file, string $disk, string $savePath, string $fileHash, string $type, int $totalSize = 0)
    {

        $fileInfo = [
            'disk' => $disk,
            'mime_type' => $file->getOriginalMime(),
            'sha1' => $fileHash,
            'size' => $totalSize ?: $file->getSize(),
            'original_name' => $file->getOriginalName(),
            'ext' => strtolower($file->getOriginalExtension()),
            'url' => '/' . $savePath,
            'type' => $type,
            'width' => 0,
            'height' => 0,
        ];
        if ($filesite = self::checkImageAndGetSize(root_path() . 'public' . DIRECTORY_SEPARATOR . $savePath)) {
            $fileInfo['width'] = $filesite['width'];
            $fileInfo['height'] = $filesite['height'];
        }
        $fileInfo['uid'] = $this->uid;
        $UploadModel = UploadModel::where(['mime_type' => $fileInfo['mime_type'], 'sha1' => $fileInfo['sha1']])->findOrEmpty();
        if ($UploadModel->isEmpty()) {
            $UploadModel->save($fileInfo);
        }
        return $UploadModel->toArray();
    }
    /**
     * 文件上传
     */
    #[RequestMethod(['GET', 'POST'])]
    #[RequestTitle('文件上传')]
    public function file()
    {
        $response = parent::file();

        $pattern = '/^(https?:\/\/)?[a-zA-Z0-9_-]+\.[a-zA-Z0-9._-]+/';
        $isDomain = preg_match($pattern, $response['url']) === 1;
        if (!$isDomain) {
            $response['url'] = request()->domain() . $response['url'];
        }
        return $this->success('上传成功', ['url' => $response['url'], 'value' => (string)$response['id']]);
    }

    //////// 分片上传 //////////////////////////////////////////  
    public function startChunkApi(Request $request)
    {
        return parent::startChunkApi($request);
    }
    public function chunkApi(Request $request)
    {
        return parent::chunkApi($request);
    }
    public function finishChunkApi(Request $request)
    {
        return parent::finishChunkApi($request);
    }

    //////// 分片上传 //////////////////////////////////////////   
}
